package com.loe.ktui.util

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.loe.ktui.R
import kotlin.concurrent.thread

/** 加载View */
class KtLoadingView : FrameLayout
{
    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        initXML(attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        initXML(attrs)
    }

    val imageView = ImageView(context)

    var steep = 12

    var time = 40L

    private var isRun = true

    private fun initXML(attrs: AttributeSet)
    {
        setColor(Color.BLACK)

        imageView.setImageResource(R.mipmap.kt_icon_loading)
        val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
//        val margin = px(10)
//        params.setMargins(margin, margin, margin, margin)
        addView(imageView, params)

        imageView.rotationX = 0.5f
        imageView.rotationY = 0.5f

        var i = 0
        thread()
        {
            while(isRun)
            {
                Thread.sleep(time)
                post()
                {
                    imageView.rotation = 360f / steep * i++
                    if (i >= steep) i = 0
                }
            }
        }
    }

    fun setImageResource(@DrawableRes resId: Int)
    {
        imageView.setImageResource(resId)
    }

    fun setColor(color: Int)
    {
        imageView.setColorFilter(color)
    }

    override fun onDetachedFromWindow()
    {
        isRun = false
        super.onDetachedFromWindow()
    }
}